<?php
namespace app\api\service;
/**
 * Books Service
 * User: zng
 * Date: 2019/10/24
 * Time: 16:25
 */
use app\api\model\bookshelf\BooksContents;
use app\api\model\bookshelf\Books as BooksModel;
use think\Response;

class Books {

    /**
     * 根据左边栏获取对应书籍
     * @author zx
     * @date 2019-10-25
     * @return Response
     */
    public function booksBySidebar(int $id)
    {
        $cacheKey = 'api_books_list_'.$id.'_'.date("Ymd");
        $books = BooksModel::field('id,name,profiles,cover')->where('sid', $id)->all(null,'',$cacheKey);
        if ( $books->isEmpty() ) {
            return notFound('可用书籍为空');
        }
        return success($books->toArray());
    }

    /**
     * 获取书籍内容详情
     * @author zx
     * @date 2019-10-30
     * @return Response
     */
    public function read(int $id)
    {
        $details = BooksContents::with(['manager'])->Bid($id)->selectOrFail();
        if ( $details->isEmpty() ) {
            return notFound('该书籍暂无内容');
        }
        return success($details->toArray());
    }

    /**
     * 搜索相关书籍
     * @param string $search 搜索条件
     */
    public function search(string $search)
    {
        $cacheKey = 'api_books_search_'.$search.'_'.date("Ymd");
        $search = BooksModel::field('id,name,sort')
            ->union('SELECT `erm_books`.`id`,`erm_books`.`name`,`erm_books`.`sort` FROM `erm_books_contents` LEFT JOIN `erm_books` ON `erm_books_contents`.`bid`=`erm_books`.`id` WHERE (`erm_books_contents`.`name` LIKE "%'.$search.'%" OR `erm_books_contents`.`profiles` LIKE "%'.$search.'%") AND `erm_books_contents`.`status` = 0 AND `erm_books_contents`.`delete_at` IS NULL AND `erm_books`.`status` = 0 AND `erm_books`.`delete_at` IS NULL')
            ->where('(name LIKE "%'.$search.'%" OR profiles LIKE "%'.$search.'%")')
            ->all(null, '', $cacheKey);
        if ( $search->isEmpty() ) {
            return notFound('没有符合的书籍');
        }
        $res = [];
        foreach ( $search as $_search ) {
            $res[] = ['text'=>$_search->name, 'value'=>$_search->id];
        }
        return success($res);
    }

}